<script setup lang="ts">
import type { SystemAccountQuery } from '@/apis/system/accountApi'
import { nextTick, onMounted, ref, watch } from 'vue'
import { accountApi } from '@/apis/system/accountApi'

const model = defineModel<number | string>()
const loading = ref(false)
const options = ref<{
  label: string
  value: string
}[]>()

onMounted(async () => {
  if (model.value) {
    await loadOptions({ id: model.value as number })
  }
})

watch(() => model.value, async () => {
  if (model.value && (options.value && options.value?.length === 0)) {
    await loadOptions({ id: model.value as number })
  }
})

async function loadOptions(query: SystemAccountQuery) {
  loading.value = true
  try {
    const data = await accountApi.queryPage(query)
    nextTick(() => {
      options.value = data.records?.map((a) => {
        return {
          label: a.nickname!,
          value: `${a.id!}`,
        }
      })
    })
  }
  finally {
    loading.value = false
  }
}

async function remoteQuery(query: string) {
  if (query && query.length > 0) {
    await loadOptions({ nickname: query })
  }
}
</script>

<template>
  <el-select
    v-model="model"
    filterable
    remote
    :loading="loading"
    :remote-method="remoteQuery"
    clearable
    reserve-keyword
    default-first-option
  >
    <el-option v-for="o in options " :key="o.value" :label="o.label" :value="o.value" />
  </el-select>
</template>
